{% extends "base.html" %}

{% block title %}客户跟进管理{% endblock %}

{% block content %}
<div class="w-full">
    <!-- 页面标题 -->
    <div class="bg-white rounded-lg shadow mb-6">
        <div class="p-4 border-b border-gray-200">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                <h1 class="text-xl font-bold text-gray-800">客户跟进管理</h1>
                <div class="flex space-x-2 mt-4 md:mt-0">
                    {% if current_user.role in ['admin', 'manager'] %}
                    <form method="POST" action="{{ url_for('followup.send_reminders') }}" class="inline-block">
                        <button type="submit" class="px-4 py-2 bg-amber-500 hover:bg-amber-600 text-white rounded-md transition" onclick="return confirm('确定要发送跟进提醒吗？')">
                            <i class="fas fa-bell mr-2"></i> 发送提醒
                        </button>
                    </form>
                    {% endif %}
                    <button type="button" id="newFollowupBtn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                        <i class="fas fa-plus mr-2"></i> 新建跟进记录
                    </button>
                    <button type="button" onclick="window.testModal()" class="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition ml-2">
                        <i class="fas fa-bug mr-2"></i> 测试按钮
                    </button>
                    <a href="{{ url_for('followup.statistics') }}" class="px-4 py-2 bg-cyan-500 hover:bg-cyan-600 text-white rounded-md transition">
                        <i class="fas fa-chart-bar mr-2"></i> 统计报表
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- 筛选表单 -->
    <div class="bg-white rounded-lg shadow mb-6">
        <div class="p-4 border-b border-gray-200">
            <h5 class="text-lg font-medium text-gray-800 m-0">筛选条件</h5>
        </div>
        <div class="p-4">
            <form method="GET" action="{{ url_for('followup.list_followups') }}">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        {{ filter_form.customer_id.label(class="block text-sm font-medium text-gray-700 mb-1") }}
                        {{ filter_form.customer_id(class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent") }}
                    </div>
                    <div>
                        {{ filter_form.project_id.label(class="block text-sm font-medium text-gray-700 mb-1") }}
                        {{ filter_form.project_id(class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent") }}
                    </div>
                    <div>
                        {{ filter_form.manager_id.label(class="block text-sm font-medium text-gray-700 mb-1") }}
                        {{ filter_form.manager_id(class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent") }}
                    </div>
                    <div>
                        {{ filter_form.method.label(class="block text-sm font-medium text-gray-700 mb-1") }}
                        {{ filter_form.method(class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent") }}
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mt-4">
                    <div>
                        {{ filter_form.solution_support.label(class="block text-sm font-medium text-gray-700 mb-1") }}
                        {{ filter_form.solution_support(class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent") }}
                    </div>
                    <div>
                        {{ filter_form.start_date.label(class="block text-sm font-medium text-gray-700 mb-1") }}
                        {{ filter_form.start_date(class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent", placeholder="开始日期") }}
                    </div>
                    <div>
                        {{ filter_form.end_date.label(class="block text-sm font-medium text-gray-700 mb-1") }}
                        {{ filter_form.end_date(class="w-full border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent", placeholder="结束日期") }}
                    </div>
                    <div>
                        <!-- 空单元格，保持网格布局 -->
                    </div>
                </div>
                <div class="mt-4 flex justify-end">
                    {{ filter_form.submit(class="px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition") }}
                    <a href="{{ url_for('followup.list_followups') }}" class="ml-2 px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-md hover:bg-gray-50 transition">重置</a>
                </div>
            </form>
        </div>
    </div>

    <!-- 跟进记录列表 -->
    <div class="bg-white rounded-lg shadow mb-6">
        <div class="p-4 border-b border-gray-200">
            <h5 class="text-lg font-medium text-gray-800 m-0">跟进记录列表</h5>
        </div>
        <div class="p-4">
            {% if followups %}
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">客户名称</th>
                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">跟进人</th>
                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">跟进时间</th>
                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">跟进方式</th>
                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">项目</th>
                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">跟进内容</th>
                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">联系人</th>
                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">解决方案配合</th>
                            <th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        {% for followup in followups %}
                        <tr class="hover:bg-gray-50">
                            <td class="px-3 py-4 whitespace-nowrap">
                                <a href="{{ url_for('followup.view_followup', followup_id=followup.id) }}" class="text-blue-600 hover:text-blue-900">
                                    {{ followup.customer.name if followup.customer else '未知客户' }}
                                </a>
                            </td>
                            <td class="px-3 py-4 whitespace-nowrap text-sm text-gray-900">
                                {{ followup.manager.username if followup.manager else '未知' }}
                            </td>
                            <td class="px-3 py-4 whitespace-nowrap text-sm text-gray-900">
                                {{ followup.followup_time.strftime('%Y-%m-%d %H:%M') if followup.followup_time else '' }}
                            </td>
                            <td class="px-3 py-4 whitespace-nowrap">
                                <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                    {{ followup.method }}
                                </span>
                            </td>
                            <td class="px-3 py-4 whitespace-nowrap text-sm text-gray-900">
                                {% if followup.project %}
                                    <a href="{{ url_for('project.view_project', id=followup.project.id) }}" class="text-blue-600 hover:text-blue-900">{{ followup.project.name }}</a>
                                {% else %}
                                    -
                                {% endif %}
                            </td>
                            <td class="px-3 py-4 text-sm text-gray-900">
                                <div class="truncate max-w-xs" title="{{ followup.content }}">
                                    {{ followup.content[:50] }}{% if followup.content|length > 50 %}...{% endif %}
                                </div>
                            </td>
                            <td class="px-3 py-4 whitespace-nowrap text-sm text-gray-900">
                                {{ followup.contact.name if followup.contact else '-' }}
                            </td>
                            <td class="px-3 py-4 whitespace-nowrap text-sm text-gray-900">
                                {% if followup.solution_support %}
                                    {% if followup.solution_confirmed %}
                                        <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">已确认</span>
                                    {% else %}
                                        <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-amber-100 text-amber-800">待确认</span>
                                    {% endif %}
                                    {% if followup.solution_support_user %}
                                        <br><small class="text-gray-500">{{ followup.solution_support_user.username }}</small>
                                    {% endif %}
                                {% else %}
                                    <span class="text-gray-400">无</span>
                                {% endif %}
                            </td>
                            <td class="px-3 py-4 whitespace-nowrap text-sm font-medium">
                                <div class="flex space-x-1">
                                    <a href="{{ url_for('followup.view_followup', followup_id=followup.id) }}" 
                                       class="text-blue-600 hover:text-blue-900 p-1 rounded hover:bg-blue-50" title="查看">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    {% if current_user.role == 'admin' or current_user.role == 'manager' or (current_user.role == 'sales' and followup.manager_id == current_user.id) %}
                                    <a href="{{ url_for('followup.edit_followup', followup_id=followup.id) }}" 
                                       class="text-gray-600 hover:text-gray-900 p-1 rounded hover:bg-gray-50" title="编辑">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <button type="button" class="text-red-600 hover:text-red-900 p-1 rounded hover:bg-red-50 delete-followup" 
                                            data-id="{{ followup.id }}" data-name="{{ followup.customer.name if followup.customer else '未知客户' }}" title="删除">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    {% endif %}
                                </div>
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            {% if pagination.pages > 1 %}
            <nav aria-label="跟进记录分页" class="mt-4">
                <div class="flex justify-center items-center space-x-1">
                    {% if pagination.has_prev %}
                    <a href="{{ url_for('followup.list_followups', page=pagination.prev_num, **request.args) }}" 
                       class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                    {% endif %}
                    
                    {% for page_num in pagination.iter_pages() %}
                        {% if page_num %}
                            {% if page_num != pagination.page %}
                            <a href="{{ url_for('followup.list_followups', page=page_num, **request.args) }}" 
                               class="px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
                                {{ page_num }}
                            </a>
                            {% else %}
                            <span class="px-3 py-2 text-sm font-medium text-white bg-blue-600 border border-blue-600 rounded-md">
                                {{ page_num }}
                            </span>
                            {% endif %}
                        {% else %}
                        <span class="px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md">
                            ...
                        </span>
                        {% endif %}
                    {% endfor %}
                    
                    {% if pagination.has_next %}
                    <a href="{{ url_for('followup.list_followups', page=pagination.next_num, **request.args) }}" 
                       class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                    {% endif %}
                </div>
            </nav>
            <div class="text-center mt-2">
                <small class="text-gray-500">
                    显示第 {{ (pagination.page - 1) * pagination.per_page + 1 }} 至 
                    {{ pagination.page * pagination.per_page if pagination.page * pagination.per_page < pagination.total else pagination.total }} 条，
                    共 {{ pagination.total }} 条记录
                </small>
            </div>
            {% endif %}
            {% else %}
            <div class="text-center py-4">
                <i class="fas fa-clipboard-list fa-3x text-muted mb-3"></i>
                <h5 class="text-muted">暂无跟进记录</h5>
                <p class="text-muted">点击上方"新建跟进记录"按钮创建第一条跟进记录</p>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div id="deleteModal" class="fixed inset-0 z-50 hidden overflow-y-auto" aria-labelledby="modal-title" role="dialog" aria-modal="true">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                <div class="sm:flex sm:items-start">
                    <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                        <i class="fas fa-exclamation-triangle text-red-600"></i>
                    </div>
                    <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                        <h3 class="text-lg leading-6 font-medium text-gray-900" id="modal-title">
                            删除跟进记录
                        </h3>
                        <div class="mt-2">
                            <p class="text-sm text-gray-500">
                                确定要删除客户 "<span id="deleteCustomerName"></span>" 的这条跟进记录吗？
                            </p>
                            <p class="text-sm text-red-600 mt-1">此操作不可撤销！</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                <button type="button" id="confirmDelete" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 sm:ml-3 sm:w-auto sm:text-sm">
                    确认删除
                </button>
                <button type="button" id="cancelDelete" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                    取消
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 新建跟进记录模态框 -->
<div id="followupModal" class="fixed inset-0 z-50 hidden overflow-y-auto" aria-labelledby="followupModalTitle" role="dialog" aria-modal="true">
    <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" aria-hidden="true"></div>
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-900" id="followupModalTitle">
                        新建跟进记录
                    </h3>
                    <button type="button" id="closeFollowupModal" class="text-gray-400 hover:text-gray-500" aria-label="Close">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div id="followupFormContainer">
                    <!-- 表单内容将通过AJAX加载 -->
                    <div class="text-center py-4">
                        <i class="fas fa-spinner fa-spin text-primary"></i>
                        <p class="mt-2 text-gray-500">正在加载表单...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 删除确认
    const deleteModal = document.getElementById('deleteModal');
    const deleteCustomerName = document.getElementById('deleteCustomerName');
    const confirmDeleteBtn = document.getElementById('confirmDelete');
    const cancelDeleteBtn = document.getElementById('cancelDelete');
    const deleteForm = document.createElement('form');
    deleteForm.method = 'POST';
    deleteForm.id = 'deleteForm';
    
    let deleteUrl = '';
    
    // 为所有删除按钮添加点击事件
    document.querySelectorAll('.delete-followup').forEach(button => {
        button.addEventListener('click', function() {
            const followupId = this.getAttribute('data-id');
            const customerName = this.getAttribute('data-name');
            deleteUrl = `/followup/${followupId}/delete`;
            deleteCustomerName.textContent = customerName;
            deleteModal.classList.remove('hidden');
        });
    });
    
    // 确认删除
    confirmDeleteBtn.addEventListener('click', function() {
        deleteForm.action = deleteUrl;
        document.body.appendChild(deleteForm);
        deleteForm.submit();
    });
    
    // 取消删除
    cancelDeleteBtn.addEventListener('click', function() {
        deleteModal.classList.add('hidden');
    });
    
    // 点击背景关闭模态框
    deleteModal.addEventListener('click', function(e) {
        if (e.target === deleteModal) {
            deleteModal.classList.add('hidden');
        }
    });
    
    // 测试函数
    window.testModal = function() {
        console.log('测试函数被调用');
        alert('测试按钮被点击了！');
        const followupModal = document.getElementById('followupModal');
        if (followupModal) {
            followupModal.classList.remove('hidden');
            window.loadFollowupForm();
        } else {
            alert('找不到模态框');
        }
    };
    
    // 全局函数，用于直接从HTML调用
    window.showFollowupModal = function() {
        console.log('全局函数showFollowupModal被调用');
        const followupModal = document.getElementById('followupModal');
        const followupFormContainer = document.getElementById('followupFormContainer');
        
        if (followupModal && followupFormContainer) {
            followupModal.classList.remove('hidden');
            loadFollowupForm();
        } else {
            console.error('无法找到模态框或表单容器');
        }
    };
    
    // 全局函数，用于加载表单
    window.loadFollowupForm = function() {
        console.log('开始加载表单...');
        const followupFormContainer = document.getElementById('followupFormContainer');
        
        if (!followupFormContainer) {
            console.error('无法找到表单容器');
            return;
        }
        
        followupFormContainer.innerHTML = `
            <div class="text-center py-4">
                <i class="fas fa-spinner fa-spin text-primary"></i>
                <p class="mt-2 text-gray-500">正在加载表单...</p>
            </div>
        `;
        
        fetch('/followup/create_form')
                    .then(response => {
                        console.log('收到响应:', response);
                        if (!response.ok) {
                            // 检查是否是权限错误
                            if (response.status === 403) {
                                throw new Error('您没有权限创建跟进记录，请联系管理员');
                            } else if (response.status === 401) {
                                throw new Error('您需要重新登录才能创建跟进记录');
                            } else {
                                throw new Error(`服务器错误 (状态码: ${response.status})`);
                            }
                        }
                        return response.text();
                    })
                    .then(html => {
                        console.log('表单HTML加载成功');
                        followupFormContainer.innerHTML = html;
                        // 初始化表单中的JavaScript组件
                        initializeFormComponents();
                    })
                    .catch(error => {
                        console.error('加载表单失败:', error);
                        let errorMessage = error.message;
                        if (error.message.includes('Failed to fetch')) {
                            errorMessage = '网络连接失败，请检查网络连接或联系管理员';
                        }
                        followupFormContainer.innerHTML = `
                            <div class="text-center py-4">
                                <i class="fas fa-exclamation-triangle text-red-500"></i>
                                <p class="mt-2 text-gray-500">加载表单失败</p>
                                <p class="mt-1 text-sm text-gray-400">${errorMessage}</p>
                                <button onclick="window.location.reload()" class="mt-3 px-4 py-2 bg-primary text-white rounded-md hover:bg-blue-600 transition">
                                    <i class="fas fa-refresh mr-2"></i>刷新页面
                                </button>
                            </div>
                        `;
                    });
    };
    
    // 全局函数，用于初始化表单组件
    window.initializeFormComponents = function() {
        // 初始化日期选择器
        if (typeof flatpickr !== 'undefined') {
            flatpickr(".datetime-picker", {
                enableTime: true,
                dateFormat: "Y-m-d H:i",
                time_24hr: true,
                locale: "zh"
            });
            
            flatpickr(".date-picker", {
                dateFormat: "Y-m-d",
                locale: "zh"
            });
        }
        
        // 初始化Select2
        if (typeof $ !== 'undefined' && $.fn.select2) {
            $('.select2').select2({
                width: '100%'
            });
        }
        
        // 处理表单提交
        const followupForm = document.getElementById('followupForm');
        if (followupForm) {
            followupForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const submitBtn = this.querySelector('button[type="submit"]');
                const originalText = submitBtn.textContent;
                
                // 显示加载状态
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>提交中...';
                
                fetch('/followup/create', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 关闭模态框
                        const followupModal = document.getElementById('followupModal');
                        if (followupModal) {
                            followupModal.classList.add('hidden');
                        }
                        // 刷新页面以显示新添加的记录
                        window.location.reload();
                    } else {
                        // 显示错误信息
                        alert(data.message || '提交失败，请检查表单信息');
                        submitBtn.disabled = false;
                        submitBtn.textContent = originalText;
                    }
                })
                .catch(error => {
                    console.error('提交表单失败:', error);
                    alert('提交失败，请稍后重试');
                    submitBtn.disabled = false;
                    submitBtn.textContent = originalText;
                });
            });
        }
    };
    
// 确保DOM完全加载后再绑定事件
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM加载完成，开始绑定事件...');
    
    // 新建跟进记录模态框处理
    const followupModal = document.getElementById('followupModal');
    const followupFormContainer = document.getElementById('followupFormContainer');
    const followupModalCloseBtn = document.getElementById('closeFollowupModal');
    
    // 获取新建跟进记录按钮
    const newFollowupBtn = document.getElementById('newFollowupBtn');
    
    console.log('新建跟进记录按钮:', newFollowupBtn);
    console.log('模态框:', followupModal);
    console.log('表单容器:', followupFormContainer);
    
    // 打开模态框时，加载表单内容
    if (newFollowupBtn) {
        console.log('找到新建按钮，绑定点击事件');
        newFollowupBtn.addEventListener('click', function(e) {
            e.preventDefault();
            console.log('点击新建跟进记录按钮');
            if (followupModal) {
                followupModal.classList.remove('hidden');
                window.loadFollowupForm();
            } else {
                console.error('无法找到模态框');
            }
        });
    } else {
        console.error('无法找到新建跟进记录按钮');
    }
    
    // 关闭模态框
    if (followupModalCloseBtn) {
        followupModalCloseBtn.addEventListener('click', function() {
            if (followupModal) {
                followupModal.classList.add('hidden');
            }
        });
    }
    
    // 点击背景关闭模态框
    if (followupModal) {
        followupModal.addEventListener('click', function(e) {
            if (e.target === followupModal) {
                followupModal.classList.add('hidden');
            }
        });
    }
});  // DOMContentLoaded结束
    
    // 初始化表单组件
    function initializeFormComponents() {
        // 初始化日期选择器
        if (typeof flatpickr !== 'undefined') {
            flatpickr(".datetime-picker", {
                enableTime: true,
                dateFormat: "Y-m-d H:i",
                time_24hr: true,
                locale: "zh"
            });
            
            flatpickr(".date-picker", {
                dateFormat: "Y-m-d",
                locale: "zh"
            });
        }
        
        // 初始化Select2
        if (typeof $ !== 'undefined' && $.fn.select2) {
            $('.select2').select2({
                width: '100%'
            });
        }
        
        // 处理表单提交
        const followupForm = document.getElementById('followupForm');
        if (followupForm) {
            followupForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const submitBtn = this.querySelector('button[type="submit"]');
                const originalText = submitBtn.textContent;
                
                // 显示加载状态
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>提交中...';
                
                fetch('/followup/create', {
                    method: 'POST',
                    body: formData,
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 关闭模态框
                        followupModal.classList.add('hidden');
                        // 刷新页面以显示新添加的记录
                        window.location.reload();
                    } else {
                        // 显示错误信息
                        alert(data.message || '提交失败，请检查表单信息');
                        submitBtn.disabled = false;
                        submitBtn.textContent = originalText;
                    }
                })
                .catch(error => {
                    console.error('提交表单失败:', error);
                    alert('提交失败，请稍后重试');
                    submitBtn.disabled = false;
                    submitBtn.textContent = originalText;
                });
            });
        }
    }
    
    // 日期选择器
    if (typeof flatpickr !== 'undefined') {
        flatpickr("#start_date", {
            dateFormat: "Y-m-d",
            locale: "zh"
        });
        
        flatpickr("#end_date", {
            dateFormat: "Y-m-d",
            locale: "zh"
        });
    }
    
    // 初始化Select2
    if (typeof $ !== 'undefined' && $.fn.select2) {
        $('.select2').select2({
            width: '100%'
        });
    }
});
</script>
{% endblock %}